package com.atguigu.yygh.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.atguigu.yygh.common.result.R;
import com.atguigu.yygh.oss.service.FileService;
import com.atguigu.yygh.oss.utils.ConstantPropertiesUtil;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {
    @Override
    public String uploadFile(MultipartFile file) {
        try {
            String endPoint = ConstantPropertiesUtil.END_POINT;
            String accessKeyId = ConstantPropertiesUtil.ACCESS_KEY_ID;
            String accessKeySecret = ConstantPropertiesUtil.ACCESS_KEY_SECRET;
            String bucketName = ConstantPropertiesUtil.BUCKET_NAME;
            //创建OSSClient实例
            OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret);
            //填写本地文件的完整路径 如果未指定 则默认从示例程序所属项目对应本地路径中上传
            InputStream inputStream = file.getInputStream();
            //保证文件名唯一
            String uuid = UUID.randomUUID().toString();
            uuid = uuid.replaceAll("-", "");

            //获取上传的文件的名称
            String filename = file.getOriginalFilename();
            filename = uuid + filename;

            //文件根据当前日期分组
            //获取当前日期变成2021/09/10   阿里云会自动创建三个目录 2021 09 10
            String dateUrl = new DateTime().toString("yyyy/MM/dd");
            filename = dateUrl + "/" + filename;

            //
            ossClient.putObject(bucketName, filename, inputStream);
            //返回上传之后文件在阿里云路径
            String url = "https://" + bucketName + "." + endPoint + "/" + filename;
            ossClient.shutdown();
            return url;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
